{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def inversions(items):\n",
    "    n = len(items)\n",
    "    if n <= 1:\n",
    "        return items, 0\n",
    "\n",
    "    # number of inversions in partitions\n",
    "    left, linv = inversions(items[:n // 2])\n",
    "    right, rinv = inversions(items[n // 2:])\n",
    "\n",
    "    inv = linv + rinv\n",
    "    llen, rlen = len(left), len(right)\n",
    "    i, j, aux = 0, 0, []\n",
    "\n",
    "    # merge and count inversions\n",
    "    for k in range(n):\n",
    "        if i < llen and j < rlen and left[i] > right[j]:\n",
    "            inv += llen - i\n",
    "            aux.append(right[j])\n",
    "            j += 1\n",
    "        elif i < llen:\n",
    "            aux.append(left[i])\n",
    "            i += 1\n",
    "        else:\n",
    "            aux.append(right[j])\n",
    "            j += 1\n",
    "    \n",
    "    return aux, inv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[29, 25, 17, 15, 6, 8, 11, 15, 7, 5]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "items = list(np.random.randint(0, 30, 10))\n",
    "items"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([5, 6, 7, 8, 11, 15, 15, 17, 25, 29], 37)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "inversions(items)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
